package org.kl.bf.web.basic;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.ExcelConfig;
import org.kl.bf.entity.basic.ExcelImport;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.entity.easyui.Json;
import org.kl.bf.service.basic.AttachmentService;
import org.kl.bf.service.basic.ExcelConfigService;
import org.kl.bf.service.basic.ExcelImportService;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/excelImportForRowEdit")
public class ExcelImportForRowEditController extends BasicController {
	@Autowired
	private ExcelImportService excelImportService;
	@Autowired
	private ExcelConfigService excelConfigService;
	@Autowired
	private AttachmentService attachmentService;

	@RequiresPermissions("excelImportForRowEdit:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/excelImportList";
	}

	@RequiresPermissions("excelImportForRowEdit:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<ExcelImport> excelImports = excelImportService.getUserExcelImport(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(excelImports.getContent());
		grid.setTotal((int) excelImports.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequiresPermissions("excelImportForRowEdit:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("excelImport") ExcelImport excelImport,
			@RequestParam(value = "detailInserted") String detailInserted, @RequestParam(value = "detailUpdated") String detailUpdated,
			@RequestParam(value = "detailDeleted") String detailDeleted, RedirectAttributes redirectAttributes) {
		excelImportService.saveExcelImport(excelImport, detailInserted, detailUpdated, detailDeleted);
		return ajaxMsg("编辑成功", true, excelImport);
	}

	// @RequiresPermissions("excelImportForRowEdit:import")
	@RequestMapping(value = "excelImport/{importNo}/{attachmentId}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelImport(@PathVariable("importNo") String importNo, @PathVariable("attachmentId") String attachmentId) {
		if (StringUtils.isBlank(importNo)) {
			return ajaxMsg("Excel导入编号不能空", false, null);
		}
		if (StringUtils.isBlank(attachmentId)) {
			return ajaxMsg("附件ID不能空", false, null);
		}
		Json json = new Json();
		try {
			int[] result = excelConfigService.importExcel(importNo, attachmentId);
			json.setMsg("导入成功[新增" + (result == null ? 0 : result[0]) + "条，更新" + (result == null ? 0 : result[1]) + "条]");
			json.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("导入失败[" + e.getMessage() + "]");
			json.setSuccess(false);
		}
		return ajaxMsg(json);
	}

	// @RequiresPermissions("excelImportForRowEdit:templet")
	@RequestMapping(value = "excelTemplet/{importNo}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String excelTemplet(@PathVariable("importNo") String importNo, HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isBlank(importNo)) {
			return ajaxMsg("Excel导入编号不能空", false, null);
		}
		ExcelImport ei = excelImportService.findByImportNo(importNo);
		if (ei == null) {
			return ajaxMsg("Excel模板[" + importNo + "]不存在", false, null);
		}
		List<ExcelConfig> ecList = excelConfigService.findByExcelImportId(ei.getId());
		// 声明一个工作薄
		Workbook workbook = new HSSFWorkbook();
		// 生成一个表格
		Sheet sheet = workbook.createSheet(ei.getImportName());
		// 产生表格标题行
		Row row = sheet.createRow(0);

		for (int i = 0, colCount = ecList.size(); i < colCount; i++) {
			Cell cell = row.createCell(i);
			RichTextString text = new HSSFRichTextString(ecList.get(i).getChineseName());
			cell.setCellValue(text);
		}
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader(
					"Content-Disposition",
					"attachment;filename=\""
							+ new String((ei.getImportName() + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"),
									"ISO8859-1") + "\"");
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@RequiresPermissions("excelImportForRowEdit:delete")
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		excelImportService.deleteExcelImport(id);
		return ajaxMsg("删除成功", true, null);
	}

	@RequiresPermissions("excelImportForRowEdit:delete")
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = excelImportService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	@RequiresPermissions("excelImportForRowEdit:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<ExcelImport> excelImport = excelImportService.getUserExcelImport(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader(
					"Content-Disposition",
					"attachment;filename=\""
							+ new String(("Excel导入配置" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("Excel导入配置", ExcelImport.class, excelImport.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@RequiresPermissions("excelImportForRowEdit:export")
	@RequestMapping(value = "excelExportConfig", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExportConfig(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<ExcelConfig> excelConfig = excelConfigService.getUserExcelConfig(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader(
					"Content-Disposition",
					"attachment;filename=\""
							+ new String(("Excel导入配置明细" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"),
									"ISO8859-1") + "\"");
			ExcelWriter.exportExcel("Excel导入配置明细", ExcelConfig.class, excelConfig.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getExcelImport(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("excelImport", excelImportService.getExcelImport(id));
		}
	}
}
